<template>
  <view class="language-page">
    <view class="list-content">
      <tui-list-cell
        padding="0"
        v-for="(item, index) in items"
        :key="index"
        @click="changeLanguage(item)"
      >
        <label class="list-item">
          <text class="title">{{ item.name }}</text>
          <tui-checkbox
            :checked="item.checked"
            :scaleRatio="1.6"
            isCheckMark
            checkMarkColor="#198fff"
          />
        </label>
      </tui-list-cell>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      items: [
        {
          value: "SYSTEM",
          name: "系统语言",
          checked: false,
        },
        {
          value: "zh-Hans",
          name: "简体中文",
          checked: false,
        },
        {
          value: "en",
          name: "English",
          checked: false,
        },
      ],
    };
  },
  onLoad() {
    this.init();
  },
  methods: {
    init() {
      let lang = uni.getStorageSync("lang");
      let sysLang = uni.getStorageSync("sysLang");
      if (!sysLang) {
        sysLang = uni.getLocale();
      }
      let languange = sysLang;
      if (sysLang == "zh-Hans") {
        languange = "简体中文";
      } else if (sysLang == "en") {
        languange = "English";
      }
      this.items[0].name += "（" + languange + "）";
      if (!lang || lang == "SYSTEM") {
        this.items[0].checked = true;
      } else {
        let v = uni.getLocale();
        this.items.forEach((e) => {
          if (e.value == v) {
            e.checked = true;
          }
        });
      }
    },
    changeLanguage(data) {
      let v = data.value;
      this.items.forEach((e) => {
        if (e.value == v) {
          e.checked = true;
        } else {
          e.checked = false;
        }
      });
      uni.setStorageSync("lang", v);
      if (v == "SYSTEM") {
        v = uni.getStorageSync("sysLang");
        if (!v) {
          v = uni.getLocale();
        }
      }
      uni.setLocale(v);
      this.$i18n.locale = v;
    },
  },
};
</script>

<style lang="scss" scoped>
@import "./language.scss";
</style>
